<template>
  <div class="flex flex-col">
    <div class="businesstop">
      <search
        :placeholder="placeholder"
        class="search"
        @onSearch="onSearch"
      ></search>
      <Tabs v-model="active" @change="changetab" class="my_tabs">
        <Tab title="公海" name="HighSeas"></Tab>
        <Tab
          title="沉寂库"
          name="SilentLibrary"
          v-if="permission != 'bd'"
        ></Tab>
        <!-- <Tab title="临时库" name="TemporaryLibrary"></Tab> -->
        <Tab title="私海" name="PrivateSea"></Tab>
        <Tab
          title="外区商机"
          name="OuterZone"
          v-if="permission != 'lead' && permission != 'bd'"
        ></Tab>
      </Tabs>
      <tabsNav @open="opensheet" ref="tabsNav" @closeTabs="closeTabs"></tabsNav>
    </div>
    <div
      class="px-10px businesslist overflow-auto flex-1"
      :class="!showCard ? 'businessNone' : ''"
      ref="businesslist"
    >
      <PullRefresh v-model="refreshing[active]" @refresh="onRefresh(active)">
        <div
          v-if="list.length === 0 && !loading"
          class="flex justify-center items-center flex-col flex-1 pt-102px pb-228px"
        >
          <VanImage
            :src="require('@/assets/business/icon_phb_wssd.png')"
            style="width: 40px; height: 40px"
          ></VanImage>
          <span class="mt-16px text">暂无商机</span>
        </div>
        <List
          v-model="loading"
          :finished="finished[active]"
          finished-text="没有更多了"
          :immediate-check="false"
          @load="onLoad"
          v-else
        >
          <cardList
            :list="list"
            @Details="details"
            :active="active"
            @update="update"
            @updatafalling="get_falling_num"
            :loading="loading"
          ></cardList>
        </List>
      </PullRefresh>
    </div>
    <card
      v-show="showCard && fallingNum > 0"
      @closeCard="closeCard"
      :fallingNum="fallingNum"
    ></card>
    <searchsheet
      ref="searchsheet"
      @opentimeFilter="opentimeFilter"
      @searchConfirm="searchConfirm"
      @reset="reset"
    ></searchsheet>
  </div>
</template>

<script>
import { Tab, Tabs, Toast, PullRefresh, List, Image as VanImage } from "vant";
import { getLocationParam } from "@/utils/tools";

import {
  busineslist,
  silenceSea,
  tempSea,
  private_sea,
  out_business,
  falling_num,
} from "@/services/business/HighSeas.js";
import cardList from "./components/cardList.vue";
import search from "./components/search.vue";
import tabsNav from "../workbench/visit/components/tabs.vue";
import searchsheet from "./components/searchsheet.vue";
import card from "./components/card.vue";
import Bus from "@/config/evenrBus";

export default {
  components: {
    Tab,
    Tabs,
    cardList,
    PullRefresh,
    List,
    search,
    tabsNav,
    searchsheet,
    card,
    VanImage,
  },
  data() {
    return {
      active: "HighSeas",
      pageNum: 1,
      list: [], //列表
      refreshing: {
        HighSeas: false,
        SilentLibrary: false,
        TemporaryLibrary: false,
        PrivateSea: false,
        OuterZone: false,
      }, //下拉刷新
      loading: false, //列表加载
      finished: {
        HighSeas: false,
        SilentLibrary: false,
        TemporaryLibrary: false,
        PrivateSea: false,
        OuterZone: false,
      },
      placeholder: "商机名称快速搜索",
      parmas: {
        pageNum: 1, //页码
        dataStatus: "", //数据状态
        lastFollowUpStatus: "",
        businessOpportunityStatus: "", //商机状态
        startTime: "",
        endTime: "",
        type: "", //商机类型
        category: "", //商机品类id
      },
      showCard: false,
      fallingNum: 0, //即将掉落的商机,
      permission: "",
      isFilter: {
        //是否筛选
        HighSeas: false,
        SilentLibrary: false,
        TemporaryLibrary: false,
        PrivateSea: false,
        OuterZone: false,
      },
      businessScoll: 0, //滚动条位置
    };
  },
  created() {
    this.get_Param();
    this.onRefresh(this.active);
    if (this.permission === "bd" || this.permission === "manage") {
      this.get_falling_num();
    }
  },
  activated() {
    if (localStorage.getItem("upateNum") === "true") {
      this.get_falling_num();
    }

    if (localStorage.getItem("updataList") === "true") {
      console.log(typeof localStorage.getItem("updataList") === "true");
      localStorage.setItem("updataList", false);
      this.onRefresh(this.active);
    } else {
      this.$refs.businesslist.scrollTop = this.businessScoll;
    }
  },
  mounted() {
    Bus.$on("handleShowCard", this.handleShowCard);
    this.$refs.businesslist.addEventListener("scroll", (e) => {
      this.businessScoll = this.$refs.businesslist.scrollTop;
      // console.log(this.businessScoll);
    });
  },
  methods: {
    get_Param() {
      let per = getLocationParam("permission");
      this.permission = per; //******** */这里的角色被我改了 应该要改回这个叫做per的变量
      console.log("我是：" + per);
      localStorage.setItem("permission", "lead"); //****** 这里也要改回per*/
    },
    // 获取列表
    get_busineslist(getlistFun, listStore, maxPage) {
      // busineslist 获取公海列表
      // silenceSea 获取沉寂库列表
      // tempSea 获取临时库列表
      // private_sea 获取私海列表
      // out_business 获取外区商机列表
      this.parmas.pageNum = this.$store.state.business[maxPage];
      getlistFun(this.parmas) //获取私海列表
        .then((res) => {
          // this.list = res.data;
          if (this.refreshing[this.active]) {
            this.$store.commit("business/set_state", {
              key: listStore,
              value: res.data,
            });
            this.list = res.data;
          } else {
            this.$store.commit("business/push_list", {
              key: listStore,
              value: res.data,
            });
            this.list = this.list.concat(res.data);
          }

          this.refreshing[this.active] = false;
          this.loading = false;
          if (res.data.length < res.pageSize) {
            this.finished[this.active] = true;
          } else {
            this.finished[this.active] = false;
          }
        })
        .catch((err) => {
          this.refreshing[this.active] = false;
          this.loading = false;
          this.finished[this.active] = true;
          let errmsg = err.errMessage || err.errMessage || err.message;
          // Toast(errmsg);
          Toast(errmsg);
        });
    },
    // 获取即将掉落的商机数
    get_falling_num() {
      console.log("888");
      localStorage.setItem("upateNum", false);
      falling_num()
        .then((data) => {
          if (data.num > 0) {
            this.fallingNum = data.num;
            this.showCard = true;
          }
          Bus.$emit("ShowCard", this.showCard);
        })
        .catch((err) => {
          // Toast(err.errMessage || err.message);
          Toast(err.errMessage || err.message);
        });
    },
    // 切换tab
    onChange(name, type) {
      let obj;
      switch (name) {
        case "HighSeas":
          obj = {
            getlistFun: busineslist,
            listStore: "HighSeaslist",
            maxPage: "HpageNumMax",
          };
          break;
        case "SilentLibrary":
          obj = {
            getlistFun: silenceSea,
            listStore: "Silentlist",
            maxPage: "SpageNumMax",
          };
          break;
        case "TemporaryLibrary":
          obj = {
            getlistFun: tempSea,
            listStore: "Temporarylist",
            maxPage: "TpageNumMax",
          };
          break;
        case "PrivateSea":
          obj = {
            getlistFun: private_sea,
            listStore: "PrivateSealist",
            maxPage: "PpageNumMax",
          };
          break;
        case "OuterZone":
          obj = {
            getlistFun: out_business,
            listStore: "OuterZoneList",
            maxPage: "OpageNumMax",
          };
          break;
      }
      if (type === 1 && this.$store.state.business[obj.listStore].length > 0) {
        // 直接取store

        this.list = this.$store.state.business[obj.listStore];
        this.loading = false;
      } else if (
        type === 1 &&
        (this.$store.state.business[obj.listStore].length == 0 ||
          this.isFilter[this.active])
      ) {
        this.get_busineslist(obj.getlistFun, obj.listStore, obj.maxPage);
      } else {
        if (this.refreshing[this.active]) {
          // 重置分页
          this.$store.commit("business/set_state", {
            key: obj.maxPage,
            value: 1,
          });
          // 重置列表
          this.$store.commit("business/set_state", {
            key: obj.listStore,
            value: [],
          });
        } else {
          this.$store.commit("business/set_state", {
            key: obj.maxPage,
            value: this.$store.state.business[obj.maxPage] + 1,
          });
        }
        // 重新加载
        this.get_busineslist(obj.getlistFun, obj.listStore, obj.maxPage);
      }
    },
    // 进入详情
    details(val) {
      this.$router.push({ name: this.active, query: { id: val.id } });
    },
    changetab() {
      this.list = [];
      this.loading = true;
      if (
        this.$refs.tabsNav.tabList.length > 0 ||
        this.refreshing[this.active]
      ) {
        this.parmas = {
          pageNum: 1, //页码
          dataStatus: "", //数据状态
          lastFollowUpStatus: "", //跟进状态
          businessOpportunityStatus: "",
          startTime: "",
          endTime: "",
          type: "", //商机类型
          category: "", //商机品类id
        };
        this.$refs.searchsheet.clear();
        this.reset();
      } else {
        this.onLoad(this.active, 1);
      }
    },
    // 重置筛选
    reset() {
      this.parmas = {
        pageNum: 1, //页码
        dataStatus: "", //数据状态
        lastFollowUpStatus: "", //跟进状态
        businessOpportunityStatus: "",
        startTime: "",
        endTime: "",
        type: "", //商机类型
        category: "", //商机品类id
      };
      this.searchConfirm([]);
      this.refreshing[this.active] = true;
    },
    // 下拉刷新
    onRefresh(name, type) {
      this.refreshing[this.active] = true;
      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      this.loading = true;
      this.finished[this.active] = false;
      this.onLoad(name, type);
    },
    onLoad(name = this.active, type = 0, time = 300) {
      setTimeout(() => {
        this.onChange(name, type);
      }, time);
    },
    // 更新列表
    update(val) {
      if (val) {
        this.refreshing[val] = true;
        this.finished[val] = false;
      }
      this.onRefresh(this.active);
    },
    // 去搜索页
    onSearch(val) {
      if (val) {
        this.$router.push({
          name: "search",
          query: { value: val, active: this.active },
        });
        // Bus.$emit("gosearch");
      }
    },
    // 筛选面板
    opensheet() {
      this.$refs.searchsheet.open();
    },
    opentimeFilter(value) {
      this.$refs.searchsheet.close();
      this.$refs.timeFilter.open(value);
    },
    // 筛选确认
    searchConfirm(val) {
      val.forEach((item) => {
        switch (item.lable) {
          case "数据状态":
            this.parmas.dataStatus = item.data.type;
            break;
          case "跟进状态":
            this.parmas.lastFollowUpStatus = item.data.type;
            break;
          case "商机状态":
            this.parmas.businessOpportunityStatus = item.data.type;
            break;
          case "进入时间":
            this.parmas.startTime = item.data[0];
            this.parmas.endTime = item.data[1];
            break;
          case "商机类型":
            this.parmas.type = item.data.type;
            break;
          case "品类":
            this.parmas.category =
              item.data.value[item.data.value.length - 1].id;
            break;
        }
      });
      if (val.length === 0) {
        this.isFilter[this.active] = false;
      } else {
        this.isFilter[this.active] = true;
      }
      this.update();
      this.$refs.tabsNav.showTab(val);
    },
    // 删除筛选
    closeTabs(row) {
      switch (row.lable) {
        case "数据状态":
          this.parmas.dataStatus = "";
          break;
        case "跟进状态":
          this.parmas.lastFollowUpStatus = "";
          break;
        case "商机状态":
          this.parmas.businessOpportunityStatus = "";
          break;
        case "进入时间":
          this.parmas.startTime = "";
          this.parmas.endTime = "";
          break;
        case "商机类型":
          this.parmas.type = "";
          break;
        case "品类":
          this.parmas.category = "";
          break;
      }
      if (this.$refs.tabsNav.tabList.length > 0) {
        this.isFilter[this.active] = true;
      } else {
        this.isFilter[this.active] = false;
      }
      this.update();
      this.$refs.searchsheet.closeTabs(row);
    },
    // 关闭卡
    closeCard() {
      this.showCard = false;
    },
    handleShowCard() {
      if (this.fallingNum > 0 && !this.showCard) {
        this.showCard = true;
      }
    },
    destroyed() {
      Bus.$off("Details");
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep.van-tabs {
  box-shadow: 0px 2px 10px 0px rgba(0, 0, 0, 0.02);
}
.businesstop {
  background-color: #fff;
  .search {
    margin-bottom: 12px;
    margin-top: 12px;
  }
  .my_tabs {
    ::v-deep .van-tabs__wrap {
      padding-left: 14px;
    }
    ::v-deep .van-tabs__nav {
      justify-content: left;
      padding-left: 0;
      .van-tab {
        margin-right: 32px;
        padding: 0;
        text-align: center;
      }
    }
  }
}
</style>
